package com.hxkcloud.patient.aerotel.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


import com.hxkcloud.patient.R;
import com.hxkcloud.patient.YjhApplication;
import com.hxkcloud.patient.aerotel.AerotelActivity;
import com.hxkcloud.patient.aerotel.domain.health.AerotelECGPdu;
import com.hxkcloud.patient.aerotel.domain.health.ECGManager;

import com.hxkcloud.patient.aerotel.util.ClsUtils;
import com.hxkcloud.patient.aerotel.util.DateUtil;
import com.hxkcloud.patient.aerotel.util.F;
import com.hxkcloud.patient.aerotel.util.Picture;
import com.hxkcloud.patient.aerotel.view.ConfirmDialog;
import com.hxkcloud.patient.aerotel.view.ShowBigPhotoHasTop;
import com.hxkcloud.patient.beans.FileUploadBean;
import com.hxkcloud.patient.dborm.LoginInfoDao;

import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.views.LoadingDialog;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by daipengfei on 16/3/26.
 */
public class EcgListAdapter extends BaseAdapter {

    private static final String TAG = EcgListAdapter.class.getSimpleName();
    private  LoadingDialog loadingDialog;
    private LayoutInflater mInflater;
    private AerotelActivity mContext = null;
    private List<AerotelECGPdu> ecgs = new ArrayList<>();
    private ArrayList<File> xmls;
    private String imgurl;
    private String bluetoothId;
    private String createdDate;
    private TextView tv_uploadEcg;
    private int index;

    public EcgListAdapter(AerotelActivity context, List<AerotelECGPdu> ecgs) {
        mContext = context;
        mInflater = LayoutInflater.from(context);
        this.ecgs = ecgs;
        loadingDialog = new LoadingDialog(context, 0);
        loadingDialog.setLoadingText("正在上传");
    }




    // 用于刷新UI
    protected Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case MessageCode.NETWORKCODE_FILEUPLOAD_SUCCESS:
                    if (msg.obj != null) {
                        List<FileUploadBean>  fileResultBeans = ( List<FileUploadBean>) msg.obj;
                        String fileurl = fileResultBeans.get(0).getFilePath();
                        if (fileurl.endsWith(".jpg")){
                            imgurl  =  fileurl;
                            YiJiaHuNetWorkUtils.FileUpload(xmls, YjhApplication.file_file, handler);
                        }else if (fileurl.endsWith(".xml")){
                            LoginInfoDao userDao = new LoginInfoDao(mContext);
                            String patientId = userDao.getUser().getPatientId();
                            String departmentId = userDao.getUser().getDepartmentId();
                            Log.i(TAG,"departmentId   = "+departmentId);
                            YiJiaHuNetWorkUtils.uploadReport(bluetoothId,createdDate,fileurl,imgurl,patientId,departmentId,handler);
                        }
                    }
                    break;
                case MessageCode.NETWORKCODE__HDCUPLOAD_SUCCESS:
                    loadingDialog.dismiss();
                    Toast.makeText(mContext,"上传成功",Toast.LENGTH_SHORT).show();
                    int i = ECGManager.markasupload(mContext, ecgs.get(index).id);//修改数据库
                    mContext.sendBroadcast(new Intent(ClsUtils.REFRESH_ECGS));
                    break;
            }

        }
    };



    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public Object getItem(int position) {
        if (position < ecgs.size()) {
            return ecgs.get(position);
        } else
            return null;
    }

    public static class ViewHolder {
        public ImageView preview;
        public TextView datetime;
        public TextView tv_uploadEcg;
        public AerotelECGPdu ecg;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final AerotelECGPdu ecg = ecgs.get(position);
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.ecg_list_item, null);
            ImageView imgv = (ImageView) convertView.findViewById(R.id.imgv_preview);
            TextView tv = (TextView) convertView.findViewById(R.id.tv_record_datetime);
            final TextView  tv_uploadEcg = (TextView) convertView.findViewById(R.id.tv_uploadEcg);

            ViewHolder vh = new ViewHolder();
            vh.preview = imgv;
            vh.datetime = tv;
            vh.tv_uploadEcg = tv_uploadEcg;
            vh.ecg = ecg;

            convertView.setTag(vh);
            Bitmap thumb = ecg.getThumbImage(mContext);
            if (thumb != null) {
                imgv.setImageBitmap(thumb);
            }
            String date = ecg.createdDate;
            try {
                date = DateUtil.normalize(date, "yyyy-MM-dd HH:mm", "yyyy-MM-dd h:mm aa");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            tv.setText(date.toUpperCase());
            Log.e(TAG,"state"+ecg.state);
//            手动上传
            if (ecg.state==1) {
                //已经上传
                tv_uploadEcg.setText("已  上  传");
                tv_uploadEcg.setClickable(false);
            } else {
                tv_uploadEcg.setText("上传心电图");
                tv_uploadEcg.setClickable(true);
            }
            //点击上传心电图
            tv_uploadEcg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(final View view) {
                    if("已  上  传".equals(tv_uploadEcg.getText().toString())){
                        Toast.makeText(mContext,"心电图已经上传", Toast.LENGTH_SHORT).show();
                        tv_uploadEcg.setClickable(false);
                        return;
                    }
                    if(!isNetworkConnected(mContext)){
                        //没有网络连接
                        Toast.makeText(mContext,"请检查手机网络", Toast.LENGTH_SHORT).show();
                    return;
                    }
                    Log.e("tv_uploadEcg=-===>", "ecg.file" + ecg.file + "ecg.id" + ecg.id);



                    index = position;
//
                    loadingDialog.show();
                    LoginInfoDao userDao = new LoginInfoDao(mContext);
                    String patientId = userDao.getUser().getPatientId();
                    Log.i(TAG,"patientId   = "+patientId);
                    File dir = mContext.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS);
                    String xmlfile = dir.getAbsolutePath() + File.separator + ecg.file + ".xml";
                    File xml = new File(xmlfile);
                    String imgfile = dir.getAbsolutePath() + File.separator + ecg.file + ".jpg";
                    Log.e("deviceSN===========>", ecg.devicesn);
                    Picture picture = new Picture(imgfile, true);
                    Bitmap param = F.getBitmapByParam(picture);//获取图片
                    F.comPressBitmapByParam(picture, param);//压缩图片
                    File imgPress = new File(picture.getZoomPath());//压缩路径

                    String bluetoothID = ecg.header.getBluetoothID();
                     createdDate = ecg.createdDate;


                    try {
                        bluetoothId = URLEncoder.encode(bluetoothID, "utf-8");
                        Log.e("bluetoothId", bluetoothId);
                        String filename = bluetoothId + "_" + ecg.createdDate.replaceAll(":| |-", "");
                        Log.e(TAG, " pdu.header.getBluetoothID()" + ecg.header.getBluetoothID());
                        Log.e(TAG, " pdu.createdDate" + ecg.createdDate);
                        Log.e(TAG, "filename" + filename);
                        //上传心电
                        List<File> images = new ArrayList<>();
                        xmls = new ArrayList<>();
                        images.add(imgPress);//压缩过的
                        xmls.add(xml);//压缩过的
                        //上传图片
                        YiJiaHuNetWorkUtils.FileUpload(images, YjhApplication.file_image, handler);

                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                }
            });
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ViewHolder vh = (ViewHolder) v.getTag();
                    AerotelECGPdu pdu = vh.ecg;
                    pdu = ECGManager.getFromCache(pdu.id);
                    if (pdu != null) {
                        String path = pdu.getPicturePath(mContext);
                        Intent intent = new Intent(mContext, ShowBigPhotoHasTop.class);
                        intent.putExtra(ShowBigPhotoHasTop.PATH, path);
                        mContext.startActivity(intent);
                    }
                }
            });

            convertView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(final View view) {
                    new ConfirmDialog(mContext, "确定要删除心电图吗？", new ConfirmDialog.OnConfirmListener() {
                        @Override
                        public void onOk(ConfirmDialog dialog) {
                            dialog.dismiss();
                            ViewHolder vh = (ViewHolder) view.getTag();
                            AerotelECGPdu pdu = vh.ecg;
                            ECGManager.removeECG(mContext, pdu.id);
                            mContext.loadECGs();
                        }
                    }).show();
                    return false;
                }
            });



        } else {
            ViewHolder vh = (ViewHolder) convertView.getTag();
            Bitmap thumb = ecg.getThumbImage(mContext);
            if (thumb != null) {
                vh.preview.setImageBitmap(thumb);
            }
            String date = ecg.createdDate;
            try {
                date = DateUtil.normalize(date, "yyyy-MM-dd HH:mm", "yyyy-MM-dd h:mm aa");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            vh.datetime.setText(date.toUpperCase());
        }
        return convertView;
    }

    /**
     * 检查手机网络状态
     * @param context
     * @return
     */
    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }
    @Override
    public int getCount() {
        return ecgs.size();
    }
}
